home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2303 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: ts17-13.tor.InfoRamp.Net!pitchl
  2. From: pitchl@tdbank.ca (Lew Pitcher)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: why is this an infinite loop?
  5. Date: Sat, 20 Jan 1996 03:06:16
  6. Organization: Toronto Dominion Bank
  7. Message-ID: <pitchl.44.00031AE4@tdbank.ca>
  8. References: <4dp9p5$jm2@news1.wolfe.net>
  9. NNTP-Posting-Host: ts17-13.tor.inforamp.net
  10. X-Newsreader: Trumpet for Windows [Version 1.0 Rev A]
  11.  
  12. In article <4dp9p5$jm2@news1.wolfe.net> neus@wolfenet.com (Bill Campbell) writes:
  13.  
  14. >Beginning c student can't figure out why this small function  to read in a 
  15. >value for the variable x causes an infinite loop when it receives unexpected 
  16. >input.
  17.  
  18. >double get_x()
  19. >{
  20. > int test;
  21. > double x;
  22.  
  23. > printf("Enter a numeric value for x: ");
  24.  
  25. > while(scanf("%lf", &x) != 1)
  26. >  {
  27. >   printf("ERROR - program expecting a number");
  28. >   printf("Enter a numeric value for x: ");
  29. >  }
  30.  
  31. > return x;
  32. >}
  33.  
  34. According to the manual, scanf() will terminate "when an input character 
  35. conflicts with the control string.  If conversion terminates on a conflicting 
  36. input character, the offending input character is left unread in the input 
  37. stream."
  38. This means that if you answered
  39.  
  40. X
  41.  
  42. to the prompt, the %lf conversion fails and 'X' stays in the buffer for the 
  43. next time scanf() is executed, and is *still* invalid for a %lf conversion. 
  44. Thus the conversion again fails, again leaving the invalid chars in the buffer 
  45. and so on.
  46.  
  47. What you need to do is clean them out (with another scanf() or something) 
  48. before reissueing the scanf("%lf",&x).
  49.  
  50. Lew Pitcher             | "I'm a little source code
  51. Toronto Dominion Bank   |  Short and Stout
  52. =======================    |  Here is my Input,
  53. Enzo Matrix - Reboot    |  And here is my out"
  54.